package com.sysassist.procmgr;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.sysassist.util.CMDExecute;

import android.util.Log;

/**
 * 获取某进程的CPU和内存使用情况
 * @author 278822
 *
 */
public class ProcessMemoryUtil {
	private static final int INDEX_FIRST = -1;
    private static final int INDEX_PID = INDEX_FIRST + 1;
    private static final int INDEX_CPU = INDEX_FIRST + 2;
    private static final int INDEX_STAT = INDEX_FIRST + 3;
    private static final int INDEX_THR = INDEX_FIRST + 4;
    private static final int INDEX_VSS = INDEX_FIRST + 5;
    private static final int INDEX_RSS = INDEX_FIRST + 6;
    private static final int INDEX_PCY = INDEX_FIRST + 7;
    private static final int INDEX_UID = INDEX_FIRST + 8;
    private static final int INDEX_NAME = INDEX_FIRST + 9;
    private static final int Length_ProcStat = 9;
    
    private List<String[]> PMUList = null;
    
    public ProcessMemoryUtil() {
    	
    }
    
    /**
     * 初始化所有进程的CPU和内存列表，用于检索每个进程的信息
     */
    public void initPMUtil() {
        PMUList = new ArrayList<String[]>();
        // 获取CPU和内存使用情况
        String resultString = getProcessRunningInfo();
        // 解析CPU和内存信息
        parseProcessRunningInfo(resultString);
    }

    /**
     * 获取CPU和内存使用情况
     * @return
     */
    private String getProcessRunningInfo() {
        Log.i("fetch_process_info", "start. . . . ");
        String result = null;
        String[] cmd = {"/system/bin/top", "-n", "1"};
		result = do_exec(cmd);
        return result;
    }
    
    /**
     * 执行CPU和内存命令
     * @param cmd Linux命令
     * @return
     */
    private String do_exec(String[] cmd) {
        String txt = "\n"; 
//    	String txt = "";
//        CMDExecute cmdexe = new CMDExecute();
        try {
//        	txt = cmdexe.run(cmd, "system/bin/");
            Process p = Runtime.getRuntime().exec(cmd);

        	InputStreamReader inStreamReader = new InputStreamReader(p.getInputStream());
            BufferedReader in = new BufferedReader(inStreamReader);
            
            String line = null;  
            while ((line = in.readLine()) != null) {  
            	txt += line + "\n";                 
            }
            inStreamReader.close();
            in.close();
        } catch (IOException e) {  
        	Log.i("fetch_process_info", "e = " + e.toString());
        }
        return txt;       
    }
    
    /**
     * 解析CPU和内存信息
     * @param infoString
     * @return
     */
    private int parseProcessRunningInfo(String infoString) {
    	String tempString = "";
        boolean bIsProcInfo = false;
        
        String[] rows = null;
        String[] columns = null;
        // 使用正则表达式分割字符串
        rows = infoString.split("[\n]+");
        
        for (int i = 0; i < rows.length; i++) {
        	tempString = rows[i];
        	if (tempString.indexOf("PID") == -1) {
        		if (bIsProcInfo == true) {
        			tempString = tempString.trim();
        			columns = tempString.split("[ ]+");
        			if (columns.length == Length_ProcStat) {
        				PMUList.add(columns);
        			}
        		}
        	} else {
        		bIsProcInfo = true;
        	}
        }
        return PMUList.size();
    }
    
    /**
     * 根据进程名获取CPU和内存信息
     * @param procName
     * @return
     */
    public String getMemInfoByName(String procName) {
        String result = "";
        
        String tempString = "";
        for (Iterator<String[]> iterator = PMUList.iterator(); iterator.hasNext();) {
            String[] item = (String[]) iterator.next();
            tempString = item[INDEX_NAME];
            if (tempString != null && tempString.equals(procName)) {
                result = "CPU:" + item[INDEX_CPU] + "  Mem:" + item[INDEX_RSS];
                break;
            }
        }
        return result;
    }
    
    /**
     * 根据PID获取CPU和内存信息
     * @param pid
     * @return
     */
    public String getMemInfoByPid(int pid) {
        String result = "";
        
        String tempString = "";
        for (Iterator<String[]> iterator = PMUList.iterator(); iterator.hasNext();) {
            String[] item = (String[]) iterator.next();
            tempString = item[INDEX_PID];
            if (tempString != null && tempString.equals(String.valueOf(pid))) {
                result = "CPU:" + item[INDEX_CPU] + "  Mem:" + item[INDEX_RSS];
                break;
            }
        }
        return result;
    }
}
